package com.boot.security;

import cn.hutool.json.JSONUtil;
import com.boot.api.ApiResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class IAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        ApiResult<?> failed = ApiResult.failed();
        if(exception instanceof BadCredentialsException){
            failed.setMessage("登陆失败，密码错误。");
        }else if(exception instanceof DisabledException){
            failed.setMessage("登陆失败，账号被禁用。");
        }else {
            failed.setMessage("登录失败，未知错误。");
        }
        response.setContentType("text/json;charset=UTF8");
        response.getWriter().write(JSONUtil.toJsonStr(failed));
    }

}
